package com.qw.flutter.bugly.callback;


import android.util.Log;

import com.tencent.bugly.crashreport.CrashReport;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @date: 2022/6/22 13:40
 * @author: lixu
 * @description: bugly捕获到异常后回调该类
 * Flutter异常和闪退都会回调当前类的2个方法，
 */
public class BuglyCatchCrashCallback extends CrashReport.CrashHandleCallback {
    /**
     * 扩展数据默认大小
     */
    private static final int EXTRA_DATA_MAX_SIZE = 30;
    private int customExtraDataSize = EXTRA_DATA_MAX_SIZE;

    /**
     * 自定义扩展数据，异常时上报
     * LinkedHashMap能保证插入的顺序
     */
    private Map<String, String> customExtraDataMap = new LinkedHashMap<>();

    public BuglyCatchCrashCallback(int size) {
        if (size > 0) {
            this.customExtraDataSize = size;
        }
    }

    public void putCustomExtraData(String key, String value) {
        if (customExtraDataMap.size() >= customExtraDataSize) {
            String firstKey = customExtraDataMap.entrySet().iterator().next().getKey();
            if (firstKey != null) {
                customExtraDataMap.remove(firstKey);
            }
        }
        customExtraDataMap.put(key, value + "\n");
    }

    /**
     * Crash处理.
     *
     * @param crashType    错误类型：CRASHTYPE_JAVA，CRASHTYPE_NATIVE，CRASHTYPE_U3D ,CRASHTYPE_ANR
     * @param errorType    错误的类型名
     * @param errorMessage 错误的消息
     * @param errorStack   错误的堆栈
     * @return 返回额外的自定义信息上报
     * 返回map会在bugly extraMessage.txt文件中体现
     */
    @Override
    public synchronized Map<String, String> onCrashHandleStart(int crashType, String errorType,
                                                               String errorMessage, String errorStack) {
        return null;
    }

    /**
     * Crash处理.
     *
     * @param crashType    错误类型：CRASHTYPE_JAVA，CRASHTYPE_NATIVE，CRASHTYPE_U3D ,CRASHTYPE_ANR
     * @param errorType    错误的类型名
     * @param errorMessage 错误的消息
     * @param errorStack   错误的堆栈
     * @return byte[] 额外的2进制内容进行上报
     * 返回数据会在bugly userExtraByteData.txt文件中体现
     */
    @Override
    public synchronized byte[] onCrashHandleStart2GetExtraDatas(int crashType, String errorType,
                                                                String errorMessage, String errorStack) {

        Map<String, String> map = new LinkedHashMap<>();
        map.put("crashType", String.valueOf(crashType) + "\n");
        map.put("errorType", errorType + "\n");
        map.put("errorMessage", errorMessage + "\n");
        map.put("errorStack", errorStack + "\n");

        //自定义数据上报
        map.putAll(customExtraDataMap);
        return map.toString().getBytes(StandardCharsets.UTF_8);
    }
}
